package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.properties.PermitAllUrlProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.task.vo.IotMsgNotifyData;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jcajce.provider.asymmetric.X509;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-08-24
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private PermitAllUrlProperties permitAllUrlProperties;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        //创建page对象放进page方法
        Page<DeviceData> page=new Page<>(dto.getPageNum(),dto.getPageSize());
        LambdaQueryWrapper<DeviceData> qw = new LambdaQueryWrapper<DeviceData>()
                .like(DeviceData::getDeviceName, dto.getDeviceName())
                .eq(DeviceData::getFunctionId, dto.getFunctionId())
                .between(ObjectUtil.isNotEmpty(dto.getStartTime()) && ObjectUtil.isNotEmpty(dto.getEndTime()), DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime());

        page=page(page,qw);
        //封装数据
        return getTableInfo(page);
    }

    private TableDataInfo getTableInfo(Page<DeviceData> page) {
        TableDataInfo tableDataInfo = new TableDataInfo<>();
        //设置数据
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }


    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量插入数据
     * @param iotMsgNotifyData
     */
    @Override
    public void batchInserDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //1.解析设备数据id
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        //根据设备id查找设备数据表
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        //判断是否存在
        if(ObjectUtil.isEmpty(device))
        {
            log.info("设备不存在");
            return;
        }


        //批量保存设备数据  获取到services集合 并且遍历
        iotMsgNotifyData.getBody().getServices().forEach(s->{
            //获取properties集合
            Map<String, Object> properties = s.getProperties();
            //判空
            if(ObjectUtil.isEmpty(properties))
            {
                return;
            }
            //获取设备上报时间
            String dateTime = s.getEventTime();
            //设置时间格式以及转换成时间
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(dateTime, "yyyyMMdd'T'HHmmss'Z'");
            //将时区设置成上海
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(localDateTime);



            List<DeviceData> list=new ArrayList<>();

            //遍历properties集合 构建设备对象 并添加到一个集合中
            properties.forEach((k,v)->{
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);//这里是从设备对象中拷贝的设备数据对象,又因为这个设备数据对象中的id是要数据库中重新生成的,所以要赋值为null
                deviceData.setCreateTime(null);
                deviceData.setFunctionId(k);
                deviceData.setDataValue(String.valueOf(v));
                deviceData.setAlarmTime(eventTime);

                list.add(deviceData);
            });


            //批量保存设备数据
            saveBatch(list);


            //将设备数据保存到redis中
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(list));
        });

    }
}
